package com.hbk.programe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// ["Dealer.name","Dealer.parent","Dealer.parent.name","Dealer.refrence","Dealer.refrence.name"]
// d.name,d.parent_id,d1.name,d.refrence_id,d2.name
// from dealer d left join dealer d1 on d.parent_id=d1.id left join dealer d2 on d.refrence_id=d2.id

public class AliasCount {
	
	private Map<String,String> map=new HashMap<String,String>();
	
	public String getAlias(String ref,String alias) {
		if(map.get(ref)==null) {
			List<String> arr=new ArrayList<>();
			for(String ali:map.values()) {
				if(ali.matches(alias+"[0-9]?")) {
					arr.add(ali);
				}
			}
			if(arr.size()>0) {
				Object[] os=arr.toArray();
				Arrays.sort(os);
				String last=os[os.length-1].toString();
				String num=last.replace(alias, "");
				if(num.length()>0) {
					num=new Integer(Integer.parseInt(num)+1).toString();
				}else {
					num="1";
				}
				alias=alias+num;
			}
			map.put(ref, alias);
			return alias;
		}else {
			return map.get(ref);
		}
	}
	
	public Map<String,String> getMap() {
		return map;
	}
	
	public static void main(String[] args) {
		AliasCount count=new AliasCount();
		String alias=count.getAlias("Dealer", "d");
		System.out.println(alias);
		alias=count.getAlias("Dealer.parent", "d");
		System.out.println(alias);
		alias=count.getAlias("Dealer.refrence.abc", "a");
		System.out.println(alias);
		alias=count.getAlias("Dealer.refrence.abc.efg", "e");
		System.out.println(alias);
		alias=count.getAlias("Dealer.refrence", "d");
		System.out.println(alias);
		alias=count.getAlias("Dealer.parent", "d");
		System.out.println(alias);
		alias=count.getAlias("Dealer.refrence", "d");
		System.out.println(alias);
		Object[] os=count.getMap().keySet().toArray();
		Arrays.sort(os);
		System.out.println(Arrays.toString(os));
	}

}
